#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
import os
import shutil
import argparse
import time

def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('--input-path', required=True)
    parser.add_argument('--output-image-path', required=True)
    args = parser.parse_args(argv)


    print("检查有没有out\ohos-arm-release\packages\phone\image\boot.img，有的话删除")
    if os.path.exists(args.output_image_path):
        os.remove(args.output_image_path)

    print("检查有没有out\ohos-arm-release\packages\phone\boot文件夹，先删除再重新生成")
    boot_dir = os.path.abspath(os.path.join(args.input_path, 'boot'))

    print("copy所需文件到boot文件夹")
    if os.path.exists(boot_dir):
        shutil.rmtree(boot_dir)
    # os.makedirs(boot_dir, exist_ok=True)

    root_path = os.path.abspath(os.path.join(args.input_path, "../../../.."))
    boot_src = os.path.abspath(os.path.join(root_path, "device/raspberrypi/rpi4b/build/boot"))
    zImage_path = os.path.abspath(os.path.join(args.input_path, 'images/zImage'))
    print("要copy到boot文件夹的源文件列表")
    src_dir_list = [
        boot_src
    ]
    for src_dir in src_dir_list:
        shutil.copytree(src_dir, boot_dir, symlinks=True)    
    shutil.copy(zImage_path, boot_dir) # copy编译好的zImage镜像到boot

    boot_img = os.path.abspath(args.output_image_path)
    dd_cmd = "dd if=/dev/zero of=" + boot_img + " bs=1M count=128"
    mkfs_cmd = "mkfs.vfat " + boot_img + " -n boot -F 32"
    mcopy_cmd = "mcopy -i " + boot_img +  " " + boot_dir + "/* ::/"
    print("将boot文件夹打包成boot.img")
    os.popen(dd_cmd + " && " + mkfs_cmd)
    time.sleep(2)
    os.popen(mcopy_cmd)
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))